#include<unistd.h>
#include<iostream>
#include<cstring>
#include<sys/wait.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>

using namespace std;

#define FORMAT "[%s@%s %s]# "

#define COMMAND_SIZE 1024

#define MAXARGV 128
char *g_argv[MAXARGV];
int g_argc;

char cwd[1024];
char cwdenv[1024];

int lastcode = 0;

#define MAXENVS 100
char *g_env[MAXENVS];
int g_envs = 0;

#define NONE_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3

int redir = NONE_REDIR;
string filename;


const char *GetUserName(){
    const char *username = getenv("USER");
    return username == NULL ? "None":username;
}
const char *GetHostName(){
    const char *hostname = getenv("HOSTNAME");
    return hostname == NULL ? "None":hostname;
}
const char *GetPwd(){
    const char *pwd = getcwd(cwd,sizeof(cwd));
    if(pwd){
        snprintf(cwdenv,sizeof(cwdenv),"PWD=%s",cwd);
        putenv(cwdenv);
    }
    return pwd == NULL ? "None":pwd;
}

const char *GetHome(){
    const char *home = getenv("HOME");
    return home == NULL ? "":home;
}

string DirName(const char *pwd){
#define SLASH "/"
    string dir = pwd;
    if(dir == SLASH) return SLASH;
    auto pos = dir.rfind(SLASH);
    if(pos == string::npos) return "BUG?";
    return dir.substr(pos+1);

}

bool cd(){
    if(g_argc == 1){
        string home = GetHome();
        if(home.empty())
            return true;
        chdir(home.c_str());
    }
    else{
        string where = g_argv[1];
        chdir(where.c_str());
    }
    return true;
}

bool echo(){
    string opt = g_argv[1];
    if(opt == "$?"){
        cout<<lastcode<<endl;
        lastcode = 0;
    }
    else if(opt[0] == '$'){
        string env_name = opt.substr(1);
        const char * env_val = getenv(env_name.c_str());
        if(env_val==NULL){
            return true;
        }
        cout<<env_val<<endl;
    }
    else{
        cout<<opt<<endl;
    }
    return true;
}

void InitEnv(){
    extern char **environ;
    g_envs = 0;
    memset(g_env,0,sizeof(g_env));
    for(int i = 0;environ[i];i++){
        g_env[i] = (char*)malloc(strlen(environ[i])+1);
        g_env[i] = environ[i];
        g_envs++;
    }
    g_env[g_envs++] = (char*)"HAHA=for_test";
    g_env[g_envs] = NULL;
    for(int i = 0;g_env[i];i++){
       putenv(g_env[i]); 
    }
    environ = g_env;
}

void MakeCommandPrompt(char *prompt,int size){
    snprintf(prompt,size,FORMAT,GetUserName(),GetHostName(),DirName(GetPwd()).c_str());
}

void PrintCoammandPrompt(){
    char prompt[COMMAND_SIZE];
    MakeCommandPrompt(prompt,sizeof(prompt));
    printf("%s",prompt);
    fflush(stdout);
}

bool GetCommandLine(char *command,int size){
    char *c = fgets(command,size,stdin);
    if(c == NULL) return false;
    command[strlen(command)-1] = 0;
    if(strlen(command) == 0) return false;
    return true;
}

bool CommandPrase(char *command){
#define SEP " "
    g_argc = 0;
    g_argv[g_argc++] = strtok(command,SEP);
    while((bool)(g_argv[g_argc++] = strtok(nullptr,SEP)));
    g_argc--;
    return true;
}

void TrimSpace(char *cmd,int& end){
    if(isspace(cmd[end]))
        end++;
}

void RedirCheck(char *command){
    filename.clear();
    redir = NONE_REDIR;
    
    int begin = 0;
    int end = strlen(command)-1;
    
    while(end>begin){
        if(command[end] == '<'){
            command[end++] = 0;
            TrimSpace(command,end);
            redir = INPUT_REDIR;
            filename = command+end;
            break;
        }
        else if(command[end] == '>'){
            if(command[end-1] == '>'){
                command[end-1] = 0;
                redir = APPEND_REDIR;
            }
            else {
                redir = OUTPUT_REDIR;
            }
            command[end++] = 0;
            TrimSpace(command,end);
            filename = command + end;
            break;
        }
        else 
            end--;
    }
}


bool CheckAndBuiltin(){
    string cmd = g_argv[0];
    if(cmd == "cd"){
        cd();
        return true;
    }
    else if(cmd == "echo"){
        echo();
        return true;
    }
    return false;
}

int Execute(){
    pid_t id = fork();
    if(id == 0){
        int fd = -1;
        if(redir == INPUT_REDIR){
            fd = open(filename.c_str(),O_RDONLY);
            if(fd<0)
                exit(1);
            dup2(fd,0);
            close(fd);
        }
        else if(redir == OUTPUT_REDIR){
            fd = open(filename.c_str(),O_CREAT | O_WRONLY | O_TRUNC, 0666);
            if(fd<0)
                exit(2);
            dup2(fd,1);
            close(fd);
        }
        else if(redir == APPEND_REDIR){
            fd = open(filename.c_str(),O_CREAT | O_WRONLY | O_APPEND, 0666);
            if(fd<0)
                exit(3);
            dup2(fd,1);
            close(fd);
        }   


        execvp(g_argv[0],g_argv);
        exit(4);
    }
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid > 0){
        lastcode = WEXITSTATUS(status);
    }
    return 0;
}

int main(){
    InitEnv();
    while(true){

        //1.打印指令行
        PrintCoammandPrompt();
    
        //2.接收指令
        char commandline[COMMAND_SIZE];
        if(!GetCommandLine(commandline,sizeof(commandline)))
            continue;

        //4.重定向分析
        RedirCheck(commandline);      
        
        //3.指令分析
        CommandPrase(commandline);
        

        //5.内建指令的识别和处理
        if(CheckAndBuiltin())
            continue;

        //6.执行命令
        Execute();        
    }
    return 0;
}
